<template>
  <div class="edit-address">
    <van-form class="form">
      <van-field
        v-model="formData.userName"
        label="姓名"
        placeholder="请输入姓名"
        :rules="[{ required: true }]"
      />
      <van-field
        v-model="formData.telNumber"
        label="手机号"
        placeholder="请输入手机号"
        :rules="[{ required: true }]"
      />

      <van-field
        v-model="formData.address"
        label="城市"
        placeholder="省份、城市、区县"
        :rules="[{ required: true }]"
        @click="showPop = true"
      />
      <van-field
        v-model="formData.detailadress"
        label="详细地址"
        placeholder="详细地址，如楼道、楼盘号等"
        :rules="[{ required: true }]"
      />
      <van-popup v-model="showPop" position="bottom" :style="{ height: '40%' }">
        <van-area
          title="标题"
          :area-list="areaList"
          @confirm="popConfirm"
          @cancel="popCancel"
        />
      </van-popup>
      <div class="checkbox">
        <van-checkbox v-model="formData.checked" shape="square"
          >设置成默认地址</van-checkbox
        >
      </div>
    </van-form>

    <div class="footer">
      <van-button type="info" class="submit" color="#b4282b" @click="onSubmit"
        >提交</van-button
      >
    </div>
  </div>
</template>
<script>
import { areaList } from "@vant/area-data";
import { saveAction, detailAction } from "@/api/addressmanage";
export default {
  data() {
    return {
      showPop: false,
      formData: {
        userName: "",
        telNumber: "",
        address: "",
        detailadress: "",
        checked: false,
      },
      addressId: "",
      areaList,
    };
  },
  methods: {
    // 城市选择点击确认后
    popConfirm(addressList) {
      console.log(addressList);
      this.showPop = false;
      this.formData.address = addressList
        .map((item) => {
          return item.name;
        })
        .join("  ");
    },
    // 城市选择点击取消后
    popCancel() {
      this.showPop = false;
    },
    onSubmit() {
      console.log("onSumit");
      saveAction({
        ...this.formData,
        openId: localStorage.getItem("openId"),
        addressId: this.addressId,
      }).then((res) => {
        console.log(res);
        if (res.data.data) {
          this.$toast("修改成功");
          this.$router.go(-1);
        }
      });
    },
  },

  created() {
    let addressId = this.$route.query.id;
    if (addressId) {
      this.addressId = addressId;
    }
    detailAction({
      id: addressId,
    }).then((res) => {
      console.log(res);
      let addressInfo = res.data.data;
      this.formData = {
        userName: addressInfo.name,
        telNumber: addressInfo.mobile,
        address: addressInfo.address,
        detailadress: addressInfo.address_detail,
        checked: addressInfo.is_default == 1,
      }
    });
  },
};
</script>
<style lang="scss">
@import "./index.scss";
</style>
